template.defaults.imports.getVideoInfo = function (videoId) {
    $.ajaxSettings.async = false;
    $.get('/listSnapshots',{
        videoId:videoId,
    },function(result){
        if (result.code == 100){
            var url = result.data.MediaSnapshot.Snapshots.Snapshot[0].Url;
            $.get('/getPlayInfo?videoId=' + videoId,function(result){
                var playVideo = '';
                for (var i = 0;i < result.data.length; i++){
                    if (result.data[i].Format == 'mp4'){
                        playVideo = result.data[i].PlayURL;
                        break;
                    }
                }
                template.defaults.imports.video = {
                    playUrl:playVideo,
                    imgUrl:url
                };
                $.ajaxSettings.async = true;
            });
        }
    });
};

template.defaults.imports.TimestampToTime = function (timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes();
    return Y + M + D + h + m ;
};

/* global pro Aliplayer*/
if ( pro && pro.showVideos){
    var html = template('video', { videoId:pro.showVideos });
    document.getElementById('ossvideo').innerHTML = html;
    $('#ossvideo .img').click(function(){
        var playerContainer = $('<div></div>').attr('id','playerContainer').css({
            position:'fixed',
            width:'100%',
            height:'100%',
            display:'none',
            top: '0',
            zIndex:'9999'
        }).appendTo(window.document.body);
        var playUrl = $(this).attr('data-url');
        var player = new Aliplayer ({
            "id": "playerContainer",
            "source": playUrl,
            "width": "100%",
            "height": "500px",
            "autoplay": true,
            "isLive": false,
            "rePlay": true,
            "playsinline": true,
            "preload": true,
            "controlBarVisibility": "hover",
            "useH5Prism": true
        }, function (player) {
            player._switchLevel = 0;
            console.log("播放器创建了。");
        });
        var closeVideo = $('<svg id="closeVideo" t="1552392959791" class="icon" style="width:0.8rem;height:0.8rem;position:absolute;top:0.1rem;right:0.1rem;cursor:pointer;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5486" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 32C246.4 32 32 246.4 32 512s214.4 480 480 480 480-214.4 480-480S777.6 32 512 32" fill="#FF2828" p-id="5487"></path><path d="M713.6 713.6c-12.8 12.8-35.2 12.8-48 0l-153.6-153.6-153.6 153.6c-12.8 12.8-35.2 12.8-48 0s-12.8-35.2 0-48l153.6-153.6-153.6-153.6c-12.8-12.8-12.8-35.2 0-48s35.2-12.8 48 0l153.6 153.6 153.6-153.6c12.8-12.8 35.2-12.8 48 0s12.8 35.2 0 48l-153.6 153.6 153.6 153.6c16 12.8 16 35.2 0 48z" fill="#FFFFFF" p-id="5488"></path></svg>');
        playerContainer.append(closeVideo).show();
        closeVideo.click(function(){
            var _parent = $(this).parent();
            player.stop();
            _parent.remove();
        });
    });
    $('#ossvideo .img .del').click(function(e){
        $(this).parent().remove();
        $('#showVideos').val('');
        registerVideoCount(-1);
        e.stopPropagation();
    });
}


/* global FormData visitUrl*/
/* global getCookie */
/* global template */
/* global timeToTimestamp */
/* global proDetails hex_md5 */

var imgList = {};
var list = [];
var imgPath = '';
(function ($) {
    //一级分类
    $.ajax({
        type: 'POST',
        url: "/antique/api/sysDict/query_list",
        data: {
            type: "firstcategory",
            "token": getCookie('token')
        },
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                if (result.data && result.data.list && result.data.list.length > 0) {
                    var list = result.data.list;
                    for (var i = 0; i < list.length; i++) {
                        if (pro.firstCategory == list[i].id){
                            $("#firstCategory").append("<option value='" + list[i].id + "' selected>" + list[i].label + "</option>");
                            selectSecondCategory(pro.firstCategory);
                        } else {
                            $("#firstCategory").append("<option value='" + list[i].id + "'>" + list[i].label + "</option>");
                        }
                    }
                }
            }
        }
    });

    $.ajax({
        type: 'POST',
        url: "/antique/api/mallAuction/manage/query_list",
        data: {
            token:getCookie('token'),
            start:0,
            limit:20,
            state:0
        },
        success: function (result) {
            if (result.code == 0) {
                if (result.data && result.data.list && result.data.list.length > 0) {
                    var list = result.data.list;
                    for (var i = 0; i < list.length; i++) {
                        $("#selectedSpecial").append("<option value='" + list[i].id + "'>" + list[i].name + "</option>");
                    }
                }
            }
        }
    });
})(jQuery);

$("#firstCategory").change(function () {
    var value = $("#firstCategory").val();
    selectSecondCategory(value);
});

function selectSecondCategory(value){
    $("#secondCategory").empty();
    $("#secondTags").html('');
    $.ajax({
        type: 'POST',
        url: "/antique/api/sysDict/query_list",
        data: {
            type: "secondcategory",
            "token": getCookie('token'),
            parentId: value
        },
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                if (result.data && result.data.list && result.data.list.length > 0) {
                    var list = result.data.list;
                    $("#secondCategory").append("<option value='' disabled selected style='display:none;'>请选择</option>>");
                    for (var i = 0; i < list.length; i++) {
                        if (pro.secondCategory == list[i].id){
                            $("#secondCategory").append("<option value='" + list[i].id + "' selected>" + list[i].label + "</option>");
                        } else {
                            $("#secondCategory").append("<option value='" + list[i].id + "'>" + list[i].label + "</option>");
                        }
                    }
                }
            }
        }
    });
}

$("#secondCategory").change(function () {
    var value = $("#secondCategory").val();
    $.ajax({
        type: 'POST',
        url: "/antique/api/sysDict/query_lower_list",
        data: {
            parentId: value
        },
        dataType: "json",
        success: function (result) {
            if (result.code == 0) {
                if (result.data) {
                    var list = result.data;
                    var html = template('secondTagsContent', list);
                    document.getElementById('secondTags').innerHTML = html;
                } else {
                    $("#secondTags").html('');
                }
            }
        }
    });
});

function delImg(img) {
    var allImg = $("#showImages").val();
    if (img && allImg) {
        var imgPath2 = '';
        var imgs = allImg.split(',');
        list = [];
        imgList = {};
        for (var i = 0; i < imgs.length; i++) {
            if (imgs[i] != img) {
                var a = {};
                a.path = imgs[i];
                list.push(a);
                imgPath2 = imgPath2 + imgs[i] + ",";
            }
        }
        imgPath = imgPath2;
        imgList.list = list;
        imgList.imgPath = imgPath2.substring(0, imgPath2.length - 1);
        var html = template('pho', imgList);
        document.getElementById('uploaderFiles').innerHTML = html;
    }
}

/**$("#uploaderInput").on("change", function(e) {
    var file = e.target.files;
    for (var i = 0;i < file.length; i++){
        
        file[i] && handlePic(file[i],2160,function(res){
            if (res.code == 0){
                var a = {};
                a.path = res.data.path;
                imgPath = imgPath + res.data.path + "," ;
                list.push(a);
                imgList.list = list;
                imgList.imgPath = imgPath.substring(0, imgPath.length - 1);
                var html = template ('pho', imgList);
                document.getElementById('uploaderFiles').innerHTML = html;
            } else {
                $.toast(res.message, "cancel");
            }
        });
    }
}); */
$("#detailsDesc").keyup(function () {
    var value = $.trim(this.value);
    var descLength = $.trim(this.value).length;
    if (descLength <= 200) {
        $("#descNumber").html(descLength);
    } else {
        $("#detailsDesc").val(value.substring(0, 200));
    }
});

//限制价格相关的输入内容,加价幅度不能为0
$('input[type="number"]').bind("input propertychange",function(event){
    if ($(this).attr('id') == 'bidIncrementPrice'){
        if ($(this).val() == 0){
            $(this).val('');
        }
    } else {
        $(this).val(~~$(this).val());
    }
});

/* global getBeforeDate */
$("#planEndDate").click(function () {
    $("#planEndDateSelecter").popup();
    $("#planEndDateSelecter").empty();
    //生成5天内的选择时间
    var timestamp = (new Date()).valueOf();
    var startDate = new Date(timestamp);
    //设置当前时间加5分钟,加10分钟,加30分钟
    var add5Minute = new Date(timestamp + 5 * 60 * 1000);
    var add10Minute = new Date(timestamp + 10 * 60 * 1000);
    var add30Minute = new Date(timestamp + 30 * 60 * 1000);
    //快速截拍5分钟，10分钟，30分钟
    $('<div></div>').addClass('title').text('快速截拍').appendTo('#planEndDateSelecter');
    var container = $('<div></div>').addClass('container').appendTo('#planEndDateSelecter');
    $('<div></div>').addClass('item').text('5分钟').attr({ 
        datetime : add5Minute.getFullYear() + "-" + prefixInteger(add5Minute.getMonth() + 1,2) + "-" + prefixInteger(add5Minute.getDate(),2) + " " + prefixInteger(add5Minute.getHours(),2) + ":" + prefixInteger(add5Minute.getMinutes(),2)  
    }).appendTo(container);
    $('<div></div>').addClass('item').text('10分钟').attr({ 
        datetime : add10Minute.getFullYear() + "-" + prefixInteger(add10Minute.getMonth() + 1,2) + "-" + prefixInteger(add10Minute.getDate(),2) + " " + prefixInteger(add10Minute.getHours(),2) + ":" + prefixInteger(add10Minute.getMinutes(),2)  
    }).appendTo(container);
    $('<div></div>').addClass('item').text('30分钟').attr({ 
        datetime : add30Minute.getFullYear() + "-" + prefixInteger(add30Minute.getMonth() + 1) + "-" + prefixInteger(add30Minute.getDate(),2) + " " + prefixInteger(add30Minute.getHours(),2) + ":" + prefixInteger(add30Minute.getMinutes(),2)  
    }).appendTo(container);
    $('<div></div>').addClass('auto-height').appendTo(container);

    var days = $('<div></div>').addClass('days').appendTo('#planEndDateSelecter');
    for (var i = 0; i < 5; i++) {
        var endDate = new Date(timestamp + i * 24 * 60 * 60 * 1000);
        var day = $('<div></div>').addClass('day').appendTo(days);
        $('<div></div>').addClass('title').text((endDate.getMonth() + 1) + '月' + (endDate.getDate()) + '日').appendTo(day);
        var _container = $('<div></div>').addClass('container').appendTo(day);
        for (var j = 1; j < 24; j++) {
            if ((i == 0) ? (startDate.getHours() < j && j > 9) : (j > 9)) {
                $('<div></div>').addClass('item').attr({
                    datetime:endDate.getFullYear() + "-" + prefixInteger(endDate.getMonth() + 1,2) + "-" + prefixInteger(endDate.getDate(),2) + " " + prefixInteger(j,2) + ":00" 
                }).click(function () {

                }).text(prefixInteger(j,2) + ':00').appendTo(_container);
            }
        }
        $('<div></div>').addClass('auto-height').appendTo(_container);
    }
    $('#planEndDateSelecter .container .item').click(function(){
        var datetime = $(this).attr('datetime');
        $('#planEndDate').val(datetime);
        $('#planEndDateSelecter').hide();
    });
});

function checkDate(enddate) {
    try {
        // 获取毫秒
        var beginsecond = new Date().getTime();
        var endsecond = enddate.getTime();
        var days = (endsecond - beginsecond) / (24 * 3600 * 1000);
        if (days > 5) {
            $.toast("截拍时间不能超过当前5天");
            return;
        }
    } catch (e) {
        $.toast("比较时间出错，原因：" + e.message);
        return;
    }
}

function changeDate(str) {
    try {
        var newstr = str.replace(/-/g, '/');
        return new Date(newstr);
    } catch (e) {
        $.toast("转换时间出错，原因：" + e.message);
        return;
    }
}
var submiting = false;
function puilcPro(state) {
    if(submiting)return false;
    submiting = true;
    var tagSelect = $("#secondTags").find('select');
    var tags = '';
    tagSelect && tagSelect.each(function (index, element) {
        tags = tags + $(this).val() + ',';
    });
    if (tags) {
        tags = tags.substring(0, tags.length - 1);
    }
    var id = $("#proId").val();
    var auctionId = $("#auctionId").val();
    var name = $("#name").val();
    var price = $("#price").val();
    var bidIncrementPrice = $("#bidIncrementPrice").val();
    var sizeDesc = $("#sizeDesc").val();
    var firstCategory = $("#firstCategory").children('option:selected').val();
    var secondCategory = $("#secondCategory").children('option:selected').val();
    var planEndDate = $("#planEndDate").val();
    var bondMoney = $("#bondMoney").val();
    var detailsDesc = $("#detailsDesc").val();
    var showImages = $("#showImages").val();
    var showVideos = $('#showVideos').val();
    var fixedPrice = $("#fixedPrice").val();
    var logisticsFee = $('#logisticsFee').val();
    var isAgree = $('#weuiAgree').prop("checked");
    if (firstCategory == '') {
        $.toast("分类不能为空", "cancel");
        submiting = false;
        return;
    }
    if (secondCategory == '' || typeof secondCategory == 'undefined') {
        $.toast("分类不能为空", "cancel");
        submiting = false;
        return;
    }
    if (name == '') {
        $.toast("名称不能为空", "cancel");
        submiting = false;
        return;
    }
    if (sizeDesc == '') {
        $.toast("尺寸不能为空", "cancel");
        submiting = false;
        return;
    }
    if (detailsDesc == '') {
        $.toast("描述不能为空", "cancel");
        submiting = false;
        return;
    }
    if (typeof showImages == 'undefined' || showImages == '') {
        $.toast("请上传图片", "cancel");
        submiting = false;
        return;
    }
    if (price == '') {
        $.toast("价格不能为空", "cancel");
        submiting = false;
        return;
    }
    if (bidIncrementPrice == '') {
        $.toast("加价幅度不能为空", "cancel");
        submiting = false;
        return;
    }
    if (!auctionId && planEndDate == '' && (typeof(type) == 'undefined' || type =='') ) {
        $.toast("截拍日期不能为空", "cancel");
        submiting = false;
        return;
    } else if (!auctionId && (planEndDate != '' && typeof(planEndDate) != 'undefined')) {
        //判断截拍时间不能超过当前5天
        try {
            // 获取毫秒
            var beginsecond = new Date().getTime();
            var endsecond = changeDate(planEndDate).getTime();
            var days = (endsecond - beginsecond) / (24 * 3600 * 1000);
            if (days > 5) {
                $.toast("截拍时间不能超过当前5天");
                submiting = false;
                return;
            }
        } catch (e) {
            $.toast("比较时间出错，原因：" + e.message);
            submiting = false;
            return;
        }
    }
    if(!isAgree){
        $.toast("请同古今在线交易规则后才能成功上传藏品", "cancel");
        submiting = false;
        return;
    }
    /* if (bondMoney == ''){
        $.toast("保证金不能为空", "cancel");
        return;
    } */
    var params = {};
    params.id = id;
    params.auctionId = auctionId;
    params.type = 1; //1拍卖商品 2普通商品)
    params.name = name;
    params.price = price;
    params.bidIncrementPrice = bidIncrementPrice;
    params.fixedPrice = fixedPrice;
    params.sizeDesc = sizeDesc;
    params.firstCategory = firstCategory;
    params.secondCategory = secondCategory;
    params.logisticsFee = logisticsFee;
    if (!auctionId && (typeof(planEndDate)!='undefined' && planEndDate != '')) {
        planEndDate = planEndDate.replace(/\-/g,"/");
        params.planEndDate = new Date(planEndDate.toString()).getTime();
    }
    params.bondMoney = bondMoney;
    params.detailsDesc = detailsDesc;
    params.showImages = showImages;
    if (showVideos && showVideos != '') {
        params.showVideos = showVideos;
    }
    params.delayMinutes = 5;
    params.tags = tags;
    params.token = getCookie('token');

    if (id) {
        upPro(params, state);
    } else {
        addPro(params, state);
    }
}

function addPro(params, state) {
    delete params.id;
    $.ajax({
        type: 'POST',
        url: "/antique/api/mallProduct/manage/add_product",
        data: params,
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                if (state == 1) { //0仓库和专场 1出售中
                    pubilcPro(res.data.id, params);
                } else {
                    $.toast("上传成功!谢谢您的使用!");
                    window.setTimeout(function () {
                        submiting = false;
                        if(isMiniProgram()){
                            if(isOutStock == 'true'){
                                wx.miniProgram.redirectTo({
                                    url: '/pages/collectList'
                                });
                            } else {
                                wx.miniProgram.navigateBack();
                            }
                        } else {
                            goPreUrl();
                        }
                    }, 1000);
                }
            } else {
                $.toast(res.message, "cancel");
                submiting = false;
            }
        }
    });
}

function upPro(params, state) {
    $.ajax({
        type: 'POST',
        url: "/antique/api/mallProduct/manage/update_product",
        data: params,
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                if (state == 1) {
                    pubilcPro(params.id, params);
                } else {
                    $.toast("修改成功，谢谢您的使用!");
                    window.setTimeout(function () {
                        submiting = false;
                        if(isMiniProgram()){
                            if(isOutStock == 'true'){
                                wx.miniProgram.redirectTo({
                                    url: '/pages/collectList'
                                });
                            } else {
                                wx.miniProgram.navigateBack();
                            }
                        } else {
                            goPreUrl();
                        }
                    }, 1000);
                }
            } else {
                $.toast(res.message, "cancel");
                submiting = false;
            }
        }
    });
}

var payDepositDialog = null;
function pubilcPro(id, proParams) {
    var params = {};
    params.id = id;
    params.token = getCookie('token');
    if (proParams.bondMoney != '' && parseFloat(proParams.bondMoney) > 0) {
        //支付保证金
        $("#payMoney").html(proParams.bondMoney);
        $("#payId").val(id);
        payDepositDialog = $("#pay_deposit").popup();
    } else {
        submitAdd(params);
    }
}

/* global servicePay */
$("#confirmBondPay").click(function () {
    var type = $("input[name='radioPay']:checked").val();
    var id = $("#payId").val();
    var payMoney = $("#payMoney").html();
    if (id == '') {
        $.toast("参数错误", "cancel");
        return;
    }
    if (type == 1) {
        passwordPay(id);
    } else if (type == 2) {
        /* global isMiniProgram wx */
        if (isMiniProgram()) { //小程序就跳转小程序支付
            var params = {
                type: 140, //支付类型
                id: id, //关联id
                payMoney: payMoney, //支付金额
                content: '缴纳竞拍保证金', //订单说明
                jumpUrl: '', //支付成功后跳转地址  为空返回当前页面 不可以带 ? 和 &
            };
            wx.miniProgram.navigateTo({
                url: "/pages/pay/index?params=" + JSON.stringify(params)
            });
            submiting = false;
        } else {
            $.post('/antique/api/onlinePay/wxpay/create_wxpay', {
                token: getCookie('token'),
                type: 140,
                appSource: 1,
                keyId: id,
                money: servicePay(payMoney),
                content: '缴纳竞拍保证金' + payMoney
            }, function (result) {
                var appId = result.data.appid;
                var nonceStr = result.data.nonce_str;
                var prepay_id = result.data.prepay_id;
                var mch_id = result.data.mch_id;
                /* global goWeiPay */
                goWeiPay(appId, nonceStr, prepay_id, mch_id);
                submiting = false;
            });
        }
    }
});

function passwordPay(id) {
    /* global havePayPwd */
    havePayPwd (function(havePwd) {
        if (havePwd) {
            $.modal({
                title: "请输入支付密码",
                text: '<input class="weui-input weui-prompt-input" type="password" id="password"  placeholder="没有设置密码可不填" />',
                buttons: [{
                        text: "取消",
                        className: "default"
                    },
                    {
                        text: "确定",
                        onClick: function () {
                            var password = $("#password").val();
                            var params = {};
                            params.id = id;
                            params.token = getCookie('token');
                            params.payPass = '';
                            var time = timeToTimestamp(new Date());
                            if (password == '') {
                                params.payPass = hex_md5(time + '').toUpperCase();
                            } else {
                                var passwords = hex_md5(password).toUpperCase();
                                params.payPass = hex_md5(passwords + time).toUpperCase();
                            }
                            params.time = time;
                            submitAdd(params);
                        }
                    }
                ]
            });
        } else {
            var password = '';
            var params = {};
            params.id = id;
            params.token = getCookie('token');
            var time = timeToTimestamp(new Date());
            params.payPass = '';
            if (password == '') {
                params.payPass = hex_md5(time + '').toUpperCase();
            } else {
                var passwords = hex_md5(password).toUpperCase();
                params.payPass = hex_md5(passwords + time).toUpperCase();
            }
            params.time = time;
            submitAdd(params);
        }
    });
}

function submitAdd(params,callback) {
    $.ajax({
        type: 'POST',
        url: "/antique/api/mallProduct/manage/publish_product",
        data: params,
        dataType: "json",
        success: function (res) {
            if (res.code == 0) {
                $.toast("上传成功!谢谢您的使用!");
                window.setTimeout(function () {
                    submiting = false;
                    if(isMiniProgram()){
                        if(isOutStock == 'true'){
                            wx.miniProgram.redirectTo({
                                url: '/pages/collectList'
                            });
                        } else {
                            wx.miniProgram.navigateBack();
                        }
                    } else {
                        goPreUrl();
                    }
                }, 1000);
            } else {
                submiting = false;
                $.toast(res.message, "cancel");
            }
        }
    });
}

function prefixInteger(num, n) {
    return (Array(n).join(0) + num).slice(-n);
}

//显示保证金说明
var isFirstShow = true;
function showExplain(){
    if(isFirstShow){
        $('#bond_desc').popup();
        isFirstShow = false;
    }
}

var salerAgreementDialog = null;
$('#viewAgree').click(function(){
    salerAgreementDialog = $("#salerAgreement").popup();
});

$('#salerAgreement .close').click(function(){
    salerAgreementDialog.closePopup();
});

$('#cancelBondPay').click(function(){
    submiting = false;
    payDepositDialog.closePopup();
});